import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import { SUCCESS_CODE, UN_LOGIN_CODE, API_BASE_URI } from '@/const'
import { clearLocalStorage } from '@/utils'

const service = axios.create({
  baseURL: API_BASE_URI, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 6000 // request timeout
})

service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
service.defaults.headers.put['Content-Type'] = 'application/json;charset=UTF-8'

// 请求拦截器
service.interceptors.request.use(
  config => {
    // before request
    return config
  },
  error => {
    // request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    const url = response.config.url
    // ignoreError 是否在axios拦截中不弹错误信息
    const ignoreError = /ignoreError=1/.test(url)

    // 如果等于SUCCESS_CODE，则直接返回res数据
    if (res.code === SUCCESS_CODE) {
      return res
    }
    // 如果是未登录，则转至登录页
    if (res.code === UN_LOGIN_CODE) {
      if (!ignoreError) {
        Message({
          message: res.msg,
          type: 'error',
          duration: 3000
        })
      }
      clearLocalStorage()
      // 如果不是登录页，则跳到登录页
      if (!/^#\/login/i.test(window.location.hash)) {
        console.log('go login')
        router.push('/login')
        return false
      }
    }
    // 其他是接口服务提示的错误
    else {
      if (!ignoreError) {
        Message({
          message: res.msg || '接口发生错误',
          type: 'error',
          duration: 3000
        })
      }
    }
    // 不是SUCCESS_CODE的，都走catch
    return Promise.reject(res || 'Error')
  },
  error => {
    console.log('err', error)
    Message({
      message: error.message,
      type: 'error',
      duration: 3000
    })
    return Promise.reject(error)
  }
)

const get = (uri, data, config) => service.get(uri, { params: data }, config)

const post = (uri, data, config) => service.post(uri, data, config)

const put = (uri, data, config) => service.put(uri, data, config)

const ax_delete = (uri, data, config) => service.delete(uri, { params: data }, config)

export {
  get,
  post,
  put,
  ax_delete
}

export default service
